package com.xinlong.shop.api.site;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.core.site.entity.Article;
import com.xinlong.shop.core.site.service.IArticleService;
import javax.validation.Valid;

/**
 * <p>
 * 文章列表 前端控制器
 * </p>
 *
 * @author Sylow
 * @since 2023-04-13
 */
@RestController
@RequestMapping("/site/article")
public class ArticleController {

    private final IArticleService articleService;

    public ArticleController(IArticleService articleService) {
        this.articleService = articleService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R page(Integer current, Integer size){
        Page<Article> page = new Page<>(current, size);
        page = this.articleService.page(page);
        return R.success("操作成功", page);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public R save(@Valid @RequestBody Article article ){
        Long time = DateUtil.currentSeconds();
        article.setUpdateTime(time);
        article.setCreateTime(time);
        this.articleService.save(article);
        return R.success("操作成功");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public R update(@Valid @RequestBody Article article, @PathVariable("id") Integer id){
        Long time = DateUtil.currentSeconds();
        article.setUpdateTime(time);
        this.articleService.update(article, id);
        return R.success("操作成功",article);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public R delete(@PathVariable("id") Integer id){
        this.articleService.delete(id);
        return R.success("删除成功");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public R get(@PathVariable("id") Integer id){
        Article article = this.articleService.getById(id);
        return R.success("操作成功",article);
    }

    @RequestMapping(value = "/status", method = RequestMethod.PUT)
    public R updateStatus(Integer id, Integer status){

        if (status == null) {
            status = 0;
        }

        this.articleService.updateStatus(id, status);
        return R.success();
    }

}
